package ren.kane.phoenix.util.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author renrk(1275) on 2019-07-30 5:14 PM
 **/
public class ObjectStreamTest {

    private static final String TMP_FILE = "box.tmp";

    private static void testWrite() {
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("dir", TMP_FILE)));
            objectOutputStream.writeBoolean(true);
            objectOutputStream.writeByte((byte) 65);
            objectOutputStream.writeChar('a');
            objectOutputStream.writeInt(20190730);
            objectOutputStream.writeFloat(3.14F);
            objectOutputStream.writeDouble(1.414D);
            Map<String, String> map = new HashMap<>();
            map.put("one", "red");
            map.put("two", "green");
            map.put("three", "blue");
            objectOutputStream.writeObject(map);
            Box box = new Box("desk", 80, 50);
            objectOutputStream.writeObject(box);
            objectOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void testRead() {
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File("dir", TMP_FILE)));
            System.out.printf("boolean:%b\n", objectInputStream.readBoolean());
            System.out.printf("byte:%d\n", (objectInputStream.readByte() & 0xff));
            System.out.printf("char:%c\n", objectInputStream.readChar());
            System.out.printf("int:%d\n", objectInputStream.readInt());
            System.out.printf("float:%f\n", objectInputStream.readFloat());
            System.out.printf("double:%f\n", objectInputStream.readDouble());
            Map<String, String> map = (HashMap) objectInputStream.readObject();
            Iterator iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry) iterator.next();
                System.out.printf("%-6s -- %s\n", entry.getKey(), entry.getValue());
            }
            Box box = (Box) objectInputStream.readObject();
            System.out.println("box: " + box);
            objectInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        testWrite();
        testRead();
    }
}
